package com.jinly.ryder.jenkins.service.model;

import com.alibaba.fastjson.JSONObject;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

@Data
public class JenkinsBuild {

    private boolean building;
    private String result;
    private String url;
    private Integer number;
    private Long timestamp;
    private Integer duration;//耗时
    private Integer estimatedDuration;//
    private String fullDisplayName;//构建展示名称
    private List<JenkinsArtifact> artifacts = new ArrayList<>();

    private String gitUrl;
    private String gitBranch;

    private List<GitCommitLog> gitCommitLogList = new ArrayList<>();

    public void setGitInfo(JSONObject buildJsonObject) {
        buildJsonObject.getJSONArray("actions").stream()
                .filter(o -> "hudson.plugins.git.util.BuildData".equals(((JSONObject) o).getString("_class")))
                .findAny().map(o -> (JSONObject) o)
                .ifPresent(o -> {
                    gitUrl = (String) o.getJSONArray("remoteUrls").get(0);
                    gitBranch = o.getJSONObject("lastBuiltRevision").getJSONArray("branch").getJSONObject(0).getString("name");
                    gitBranch = gitBranch.replaceAll("refs/remotes/origin/", "");
                });
    }

    public void setGitCommitLog(JSONObject buildJsonObject) {
        buildJsonObject.getJSONArray("changeSets").stream()
                .filter(o -> "hudson.plugins.git.GitChangeSetList".equals(((JSONObject) o).getString("_class")))
                .findAny().map(o -> ((JSONObject) o).getJSONArray("items"))
                .ifPresent(array -> {
                    gitCommitLogList = array.toJavaList(GitCommitLog.class);
                });
    }
}
